<template>
  <div id="globalSider" :class="{ collapsed: collapsed }">
    <div class="sider-content">
      <a-layout-sider
        v-if="loginUserStore.loginUser.id"
        class="sider"
        :width="170"
        :collapsedWidth="0"
        :collapsed="collapsed"
        breakpoint="lg"
      >
        <a-menu
          mode="inline"
          v-model:selectedKeys="current"
          :items="menuItems"
          @click="doMenuClick"
        />
      </a-layout-sider>
    </div>
    <!-- 仅在已登录时显示按钮 -->
    <div
      class="trigger"
      @click="toggleCollapsed"
      v-if="loginUserStore.loginUser.id"
    >
      <span class="trigger-content">
        <menu-unfold-outlined v-if="collapsed" />
        <menu-fold-outlined v-else />
        <span class="trigger-text">
          {{ collapsed ? '展开' : '折叠' }}
        </span>
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { h, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  PictureOutlined,
  UserOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

const loginUserStore = useLoginUserStore()
const router = useRouter()
const collapsed = ref(true)

// 菜单列表
const menuItems = [
  {
    key: '/',
    label: '公共图库',
    icon: () => h(PictureOutlined),
  },
  {
    key: '/my_space',
    label: '我的空间',
    icon: () => h(UserOutlined),
  },
  {
    key: '/ai_picture',
    label: 'AI扩图',
    icon: () => h(PictureOutlined),
  }
]

// 当前选中菜单
const current = ref<string[]>([])
router.afterEach((to, from, failure) => {
  current.value = [to.path]
})

// 路由跳转事件
const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

// 切换折叠状态
const toggleCollapsed = () => {
  collapsed.value = !collapsed.value
}
</script>

<style scoped>
#globalSider {
  position: relative;
  height: 100%;
}

.sider-content {
  height: 100%;
  overflow: hidden;
  transition: width 0.2s;
  width: 170px;
}

#globalSider.collapsed .sider-content {
  width: 0;
}

.trigger {
  position: fixed;
  left: 0px;
  top: 11%;
  transform: translateY(-50%);
  background: #fff;
  display: flex;
  align-items: center;
  cursor: pointer;
  border-radius: 0 4px 4px 0;
  box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.1);
  z-index: 100;
  transition: all 0.2s;
  padding: 8px;
  white-space: nowrap;
}

.trigger:hover {
  background: #f5f5f5;
}

.trigger-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.trigger-text {
  font-size: 14px;
  transition: opacity 0.2s, width 0.2s;
}

/* 侧边栏展开时调整按钮位置 */
#globalSider:not(.collapsed) .trigger {
  left: 172px; /* 170px + 2px */
}

/* 小屏幕隐藏文字 */
@media (max-width: 768px) {
  .trigger-text {
    display: none;
  }
}

.ant-layout-sider {
  height: 100%;
  background: #fff;
  box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.1);
}
</style>
